import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";
import { Environment } from "environments/environment";
import { NavHeaderService } from '@global/layout/default/nav-header/nav-header.service';
import { VersionsGettingRes, AliasRes } from "../shared-component/class/instance";
const HEADER = new HttpHeaders({
  'Content-Type': 'application/json'
});

@Injectable({
  providedIn: 'root'
})
export class CommonService {
  constructor(private http: HttpClient,
    private navHeaderService: NavHeaderService) { }

  getRegions(): Observable<any> {
    let url = Environment.application.serviceAPI + `/console/region/v1/regions/FCS`;
    let httpOption = {
      headers: HEADER,
    };
    return this.http.get(url, httpOption).pipe();
  }

  getRegionName(regions, regionId): string {
    for (let i = 0; i < regions.length; i++) {
      if (regions[i].regionId === regionId) {
        return regions[i].regionName;
      }
    }
  }

  base64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
      .replace(/\-/g, '+')
      .replace(/_/g, '/');

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  }

  translateRuntime(functionList) {
    let RuntimeMap = {
      "python2.7": "Python 2.7",
      "python3.6": "Python 3.6",
      "nodejs10.22": "Nodejs 10.22",
      "nodejs12.18": "Nodejs 12.18",
      "golang1": "Golang 1",
      "java8": "Java 8",
      "custom-container": "自定义镜像",
    }
    //处理runtime
    if (functionList && functionList.length > 0) {
      for (let i = 0; i < functionList.length; i++) {
        let runtime = functionList[i]['runtime'] || '';
        if (runtime && runtime != '') {
          functionList[i]['runtimeShow'] = RuntimeMap[runtime] || "Unknown Runtime";
        }
      }
    } else if (functionList && functionList.runtime) {
      let runtime = functionList['runtime'];
      functionList['runtimeShow'] = RuntimeMap[runtime] || "Unknown Runtime";
    }
  }

  hasMiddleStatus(functionList): boolean {
    let res: boolean = false;
    if (functionList) {
      for (let i = 0; i < functionList.length; i++) {
        let status = functionList[i]['status'];
        if (status == 'creating' || status == 'updating') {
          res = true;
          break;
        }
      }
    }
    return res;
  }

  transformArrayBufferToBase64(buffer) {
    var binary = '';
    var bytes = new Uint8Array(buffer);
    for (var len = bytes.byteLength, i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  }

  searchIndex(arr, key: string, value: string) {
    let index;
    if (arr && arr.length > 0) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] && arr[i][key] === value) {
          index = i;
          break;
        }
      }
    }
    return index;
  }

  getVersionList(fcsService, groupId, functionId): Promise<VersionsGettingRes> {
    return new Promise((resolve, reject) => {
      if (groupId && functionId && groupId !== '0' && functionId !== '0') {
        fcsService.getVersionList(groupId, functionId).subscribe(res => {
          if (res && res.data) {
            //this.versionList = res.data;
            resolve({
              success: true,
              versions: res.data
            })
          } else {
            resolve({
              success: false,
              versions: []
            })
          }
        }, err => {
          resolve({
            success: false,
            versions: []
          })
        })
      } else {
        resolve({
          success: false,
          versions: []
        })
      }
    })
  }

  getAliasList(fcsService, groupId, functionId): Promise<AliasRes> {
    return new Promise((resolve, reject) => {
      fcsService.getAliasList(groupId, functionId).subscribe(res => {
        if (res && res['data']) {
          resolve({
            success: true,
            alias: res['data']
          })
        } else {
          resolve({
            success: false,
            alias: []
          })
        }
      }, err => {
        resolve({
          success: false,
          alias: []
        })
      })
    })
  }

  getFunctionDuplicate(fcsService, groupId, functionName): Promise<any> {
    return new Promise((resolve, reject) => {
      fcsService.determineFunctionDuplicate(groupId, functionName).subscribe(res => {
        if (res && res['exist'] != undefined) {
          resolve({
            success: true,
            exist: res['exist']
          })
        }
        resolve({
          success: false
        })
      }, err => {
        resolve({
          success: false
        })
      })
    })
  }

  getObjectArrayIndex(objectArr, keyValue, value) {
    let targetIndex;
    if (objectArr && objectArr.length > 0) {
      for (let i = 0; i < objectArr.length; i++) {
        if (objectArr[i][keyValue] && objectArr[i][keyValue] === value) {
          targetIndex = i;
          break;
        }
      }
    }
    return targetIndex;
  }

  /*
  *获取最后一天
  */
  getLastDate(): string {
    let date = new Date();
    let lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
    let y = lastDay.getFullYear();
    let m = lastDay.getMonth() + 1;
    let d = lastDay.getDate();
    let val = y + '-' + (m > 9 ? m : '0' + m) + '-' + (d > 9 ? d : '0' + d);
    return val;
  }
}
